from flask import Flask, render_template, request
import random
import logging
import json
app = Flask(__name__)

logger = logging.getLogger()
with open('./data.json','r',encoding='utf8')as fp:
    json_data = json.load(fp)
    FOOD = json_data['food']
    POEM = random.choice(json_data['poem'])


@app.route('/', methods=['GET'])
def index():
    logger.info('GET /')
    return render_template('index.html', foods=FOOD, poem=POEM)

                                       
@app.route('/', methods=['POST'])
def handler():
    logger.info('POST /')
    logger.info(request.form)
    data = parse_params(request.form)
    result = decide(data)
    return render_template('index.html', foods=FOOD, poem=POEM, result=result)


def parse_params(raw):
    params = {}
    for k, v in raw.items():
        params[k] = int(v)
    return params
                                                     
def decide(params):
    tot = sum(params.values())
    rand = random.randint(1, tot)
    for k, v in params.items():
        rand -= v
        if rand <= 0:
            return k
